//
//  MeViewController.m
//  zhuchiren
//
//  Created by rainday on 15/1/9.
//  Copyright (c) 2015年 rainday. All rights reserved.
//

#import "MeViewController.h"
#import "MyHomePageViewController.h"
#import "SettingViewController.h"
#import "PhotosViewController.h"
#import "AudioViewController.h"
#import "DangQiViewController.h"
#import <MBProgressHUD.h>
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "LoginViewModel.h"
#import <UIImageView+AFNetworking.h>
#import "CollectionViewController.h"


# define LIST @[@[@"我的主页"],@[@"收藏",@"相册",@"声音"],@[@"档期"],@[@"设置"]]

@interface MeViewController ()<UITableViewDelegate,UITableViewDataSource,SettingViewControllerDelegate>
@property (nonatomic ,weak) IBOutlet UIView *navView;
@property (nonatomic ,weak) IBOutlet UITableView *tableView;
@property (nonatomic ,weak) IBOutlet UIButton *logoutButton;
@property (nonatomic ,weak) IBOutlet UIButton *loginButton;
@property (nonatomic ,weak) IBOutlet UIButton *registerButton;
@property (nonatomic ,weak) IBOutlet UIImageView *avatarImageView;
@property (nonatomic ,weak) IBOutlet UILabel *nameLabel;

@property (nonatomic ,strong) NSString *nickname;
@property (nonatomic ,strong) NSString *avatar;

@end
static NSString *reuseIdentify = @"cell";

@implementation MeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self setUpUI];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    self.avatar = [userDefaults objectForKey:@"avatar"];
    self.nickname = [userDefaults objectForKey:@"nickname"];
    
    @weakify(self);
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"login" object:nil] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        [self layoutWithState:YES];
        
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"logout" object:nil] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
        @strongify(self);
        [self layoutWithState:NO];
    }];
    
    [[_logoutButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        [[[LoginViewModel logout] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id x) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"logout" object:nil];
            
            
        } error:^(NSError *error) {
            
        }];
    }];
    
    RAC(_avatarImageView,image) = [RACSignal combineLatest:@[RACObserve(self, avatar)] reduce:^id(NSString *string){
        if ([string length]>0 && [string hasSuffix:@".PNG"]) {
            NSURL *url = [NSURL URLWithString:string];
            
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
            return image;
            
        }else{
            return [UIImage imageNamed:@"touxiang.jpg"];
        }
        return @(1);
    }];
    
    RAC(_nameLabel,text) = [RACSignal combineLatest:@[RACObserve(self, nickname)] reduce:^id(NSString *string){
        if ([string length]>0) {
            return string;
        }else{
            return @"竟然没昵称";
        }
        return @(1);
    }];
    
}


#pragma mark addtional setup after loading the view


- (void)setUpUI{
    _navView.layer.shadowColor = [[UIColor colorWithRed:224.0/255 green:79.0/255 blue:95.0/255 alpha:1.0] CGColor];
    _navView.layer.shadowOffset = CGSizeMake(1.0, 1.0);
    _navView.layer.shadowOpacity = .3;
    
    [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
    _tableView.backgroundColor = [UIColor clearColor];
    _logoutButton.layer.cornerRadius = 5.0f;
    _logoutButton.layer.masksToBounds = YES;
    
    
    _loginButton.layer.cornerRadius = 5.0f;
    _loginButton.layer.masksToBounds = YES;
    
    _registerButton.layer.cornerRadius = 5.0f;
    _registerButton.layer.masksToBounds = YES;
    
    _avatarImageView.layer.cornerRadius = 5;
    _avatarImageView.layer.masksToBounds = YES;
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    id token = [userDefaults objectForKey:@"token"];
    if (token) {
        [self layoutWithState:YES];
        return;
    }
    [self layoutWithState:NO];
    
    
    
}


#pragma mark 设置登录、登出界面

- (void)layoutWithState:(BOOL)isLogin{
    if (isLogin) {
        _loginButton.hidden = YES;
        _registerButton.hidden = YES;
        _avatarImageView.hidden = NO;
        _nameLabel.hidden = NO;
        _logoutButton.hidden = NO;
        
        
    }else{
        
        _loginButton.hidden = NO;
        _registerButton.hidden = NO;
        
        _avatarImageView.hidden = YES;
        _nameLabel.hidden = YES;
        _logoutButton.hidden = YES;
        
    
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



# pragma mark TableView 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentify];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.textLabel.text = LIST[indexPath.section][indexPath.row];
    cell.imageView.image = [UIImage imageNamed:LIST[indexPath.section][indexPath.row]];
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 15)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 15;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [LIST[section] count];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id token = [userDefaults objectForKey:@"token"];
    if (!token) {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"亲，您还未登录";
        [self.view addSubview:hud];
        [hud showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        }];
    
        return;
    }
    
    
    
    NSInteger section = indexPath.section;
    UIViewController *VC;
    
    
    
    if ( 0 == section) {
        VC = [[MyHomePageViewController alloc] initWithNibName:@"MyHomePageViewController" bundle:nil];
    }
    
    if (1 == section) {
        switch (indexPath.row) {
            case 0:
                VC = [[CollectionViewController alloc] initWithNibName:NSStringFromClass([CollectionViewController class]) bundle:nil];
                
                break;
            case 1:
                VC = [[PhotosViewController alloc] initWithNibName:@"PhotosViewController" bundle:nil];
                
                break;
            case 2:
                VC = [[AudioViewController alloc] initWithNibName:@"AudioViewController" bundle:nil];
                
                
                break;
            default:
                return;
                break;
        }
    }
    
    
    if (2 == section) {
        
        //档期
        
        VC = [[DangQiViewController alloc] initWithNibName:NSStringFromClass([DangQiViewController class]) bundle:nil];
              
    }
    
    if (3 == section) {
        VC = [[SettingViewController alloc] initWithNibName:@"SettingViewController" bundle:nil];
        ((SettingViewController *)VC).delegate = self;
        
    }
    
    [self presentViewController:VC animated:YES completion:nil];
    
    

}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)settingViewController:(SettingViewController *)settingViewController hasFinished:(BOOL)hasFinished{
    [settingViewController dismissViewControllerAnimated:YES completion:nil];
    self.avatar = [[NSUserDefaults standardUserDefaults] objectForKey:@"avatar"];
    self.nickname = [[NSUserDefaults standardUserDefaults] objectForKey:@"nickname"];
}
@end
